# userModel.py
from django.db import models
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import Permission  # 添加此行导入

class User(models.Model):
    """
    简单用户模型
    完全自定义的用户模型，包含用户名、密码和创建时间
    """
    
    # 用户名字段
    username = models.CharField(max_length=150, unique=True, verbose_name="用户名")
    
    # 密码字段
    password = models.CharField(max_length=128, verbose_name="密码")
    
    # 添加其他必要字段
    is_active = models.BooleanField(default=True, verbose_name="是否激活")
    is_staff = models.BooleanField(default=False, verbose_name="是否为员工")
    date_joined = models.DateTimeField(auto_now_add=True, verbose_name="加入日期")
    
    # 创建时间字段
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        db_table = "xf_user"
        verbose_name = "用户"
        verbose_name_plural = "用户"
        ordering = ["-created_at"]

    def __str__(self):
        return self.username
    
    def save(self, *args, **kwargs):
        # 如果密码未加密，则进行加密
        if not self.password.startswith('pbkdf2_') and self.password:
            self.password = make_password(self.password)
        super().save(*args, **kwargs)


# 在 userModel.py 中添加用户权限关联模型
class UserPermission(models.Model):
    """
    用户权限关联模型
    建立用户与权限的多对多关系
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_permissions', verbose_name="用户")
    permission = models.ForeignKey(Permission, on_delete=models.CASCADE, verbose_name="权限")
    granted_at = models.DateTimeField(auto_now_add=True, verbose_name="授权时间")
    
    class Meta:
        db_table = "xf_user_permission"
        verbose_name = "用户权限"
        verbose_name_plural = "用户权限"
        unique_together = ('user', 'permission')  # 确保用户和权限的组合唯一
    
    def __str__(self):
        return f"{self.user.username} - {self.permission.get_name_display()}"